package xwc.usertree;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TreeTransaction {
    private final AccountTree tree;
    private final TreeSnapshot snapshot;

    public TreeTransaction(AccountTree tree) {
        this.tree = tree;
        this.snapshot = new TreeSnapshot(tree);
    }

    public void open() {

    }

    public void commit() {
        // 自动提交，除非回滚
        tree.removeTransaction(this);
        snapshot.close();
    }

    public void rollback() {
        // 回滚到事务开始时状态
        log.warn("start rollback to {}", snapshot.getRootNodeJSON().toJSONString());
        tree.rollbackToSnapshot(snapshot);
        tree.removeTransaction(this);
        snapshot.close();
    }

    public TreeSnapshot getSnapshot() {
        return snapshot;
    }
}
